import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { useUserStore } from './userStore'
import { insertCartAPI, findNewCartListAPI, delCartAPI, mergeCartAPI } from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  const cartList = ref([])
  const addCart = async (goods) => {
    const {skuId, count} = goods
    if (isLogin.value) {
      await insertCartAPI({skuId, count})
      await updateNewList()
    } else {
      // 未登录，本地购物车
      const item = cartList.value.find(item => item.skuId === goods.skuId)
      if (item) {
          item.count = item.count + goods.count
      } else {
          cartList.value.push(goods)
      }
    }
  }

  const delCart = async (skuId) => {
    if (isLogin.value) {
      await delCartAPI([skuId])
      await updateNewList()
    } else {
      const index = cartList.value.findIndex(item => item.skuId === skuId)
      cartList.value.splice(index, 1)
      // const newList = cartList.value.filter(item => item.skuId !== skuId)
      // cartList.value = newList
    }
  }

  // 合并本地购物车，在登录时使用
  const mergeCart = async () => {
    if (cartList.value.length > 0) {
      await mergeCartAPI(cartList.value.map(item => {
          return {
              skuId: item.skuId,
              count: item.count,
              selected: item.selected
          }
      }))
    }
  }

  // 清除购物车
  const clearCart = () => {
    cartList.value = []
  }

  // 获取最新购物车列表
  const updateNewList = async () => {
    const res = await findNewCartListAPI()
    cartList.value = res.result
  }

  // 单选功能
  const singleCheck = (skuId, selected) => {
    const item = cartList.value.find(item => item.skuId === skuId)
    item.selected = selected
  }

  // 全选
  const allCheck = (selected) => {
    cartList.value.forEach(item => item.selected = selected)
  }

  // 是否全选 
  const isAll = computed(() => cartList.value.every(item => item.selected))

  // 总数量
  const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
  // 总价
  const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))

  // 已选择数量
  const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))

  // 已选择商品总份
  const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))

  return { cartList, allCount, allPrice, selectedCount, selectedPrice, isAll,
    addCart, delCart, clearCart, mergeCart, singleCheck, allCheck, updateNewList  }
}, {    
    persist: true  
})
